package top.smallway.lightbandassistant_app.UI;

import static top.smallway.lightbandassistant_app.UI.MainActivity.loginManager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;

import java.util.ArrayList;
import java.util.List;

import top.smallway.lightbandassistant_app.R;
import top.smallway.lightbandassistant_app.adapter.StartAdapter;
import top.smallway.lightbandassistant_app.data.Keys;
import top.smallway.lightbandassistant_app.network.Okhttp;

/**
 * 我的收藏页面
 * 用于显示用户收藏的歌曲列表
 */
public class MyStartActivity extends AppCompatActivity {
    // 显示歌曲列表的RecyclerView
    private RecyclerView songs;
    // 网格布局管理器
    private GridLayoutManager gridLayoutManager;
    // 歌曲列表适配器
    private static StartAdapter startAdapter;
    // 加载对话框
    private static BasePopupView xPopup;
    // 处理异步消息的Handler
    private static final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    xPopup.smartDismiss();
                    startAdapter.updateData((List<Keys>) msg.obj);
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_start);
        initview();
    }

    /**
     * 初始化页面视图
     * 包括初始化RecyclerView、设置布局管理器和适配器、显示加载对话框
     */
    private void initview() {
        songs = findViewById(R.id.songs);
        xPopup = new XPopup.Builder(this).asLoading("正在加载中").show();
        List<Keys> Starts = new ArrayList<>();
        gridLayoutManager = new GridLayoutManager(MyStartActivity.this, 2);
        songs.setLayoutManager(gridLayoutManager);
        startAdapter = new StartAdapter(Starts, MyStartActivity.this);
        songs.setAdapter(startAdapter);
        updata();
    }

    /**
     * 更新收藏列表数据
     * 在子线程中获取用户收藏的歌曲列表，并通过Handler更新UI
     */
    public static void updata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                List<Keys> StartList = Okhttp.GetStartListKey(loginManager.getID());
                message.what = 0;
                message.obj = StartList;
                mHandler.sendMessage(message);
            }
        }).start();
    }
}